package com.nnfe.fyd.feature.inquiryPrice;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.nnfe.fyd.BusKey;
import com.nnfe.fyd.R;
import com.nnfe.fyd.ShareKey;
import com.nnfe.fyd.base.ActionBarFragment;
import com.nnfe.fyd.bean.HttpResult;
import com.nnfe.fyd.feature.login.LoginActivity;
import com.nnfe.fyd.feature.main.MainActivity;
import com.nnfe.fyd.http.RetrofitSingleton;
import com.nnfe.fyd.http.Url;
import com.nnfe.fyd.utils.DialogUtil;
import com.nnfe.fyd.utils.FileUtil;
import com.nnfe.fyd.utils.ImageUtil;
import com.nnfe.fyd.utils.LogUtil;
import com.nnfe.fyd.utils.PopupViewUtil;
import com.nnfe.fyd.utils.SharePrefUtil;
import com.nnfe.fyd.utils.ToastUtil;
import com.nnfe.fyd.utils.common.DecimalTextWatcher;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;

import static android.app.Activity.RESULT_OK;

/**
 * ----------------------------------
 * Created by xyd on 2017/3/17.
 * <p/>
 * 描  述：人工询价
 * <p/>
 * 修订历史:
 * ----------------------------------
 */

public class InquiryWithFbFragment extends ActionBarFragment {

    @Bind(R.id.tv_fb_content)
    TextView tvFbContent;

    @Bind(R.id.rl_fb)
    RelativeLayout rlFb;
    @Bind(R.id.et_area_name)
    EditText etAreaName;
    @Bind(R.id.et_live_area)
    EditText etLiveArea;
    @Bind(R.id.tv_plan_for)
    TextView tvPlanFor;

    @Bind(R.id.rl_plan_for)
    RelativeLayout rlPlanFor;
    @Bind(R.id.tv_pledge)
    TextView tvPledge;

    @Bind(R.id.rl_pledge)
    RelativeLayout rlPledge;
    @Bind(R.id.et_house_location)
    EditText etHouseLocation;
    @Bind(R.id.rl_house_area)
    RelativeLayout rlHouseArea;
    @Bind(R.id.rl_secound_sum)
    RelativeLayout rlSecoundSum;
    @Bind(R.id.et_secound_sum)
    EditText etSecoundSum;

    @Bind(R.id.tv_upload_p)
    TextView tvUpload;
    @Bind(R.id.iv_upload)
    ImageView ivUpload;
    @Bind(R.id.btn_apply)
    Button btnApply;

    private ListViewAdapter listViewAdapter;
    List fbStateList = new ArrayList<String>();
    List planForList = new ArrayList<String>();
    List pledgeList = new ArrayList<String>();


    private String fbStation;
    private String houseLocation;
    private String areaName;
    private String liveArea;
    private String planFor;
    private String pledge;
    private String secondSum;


    @Override
    public Object getTitleString() {
        return "询价";
    }

    @Override
    public int getContentView() {
        return R.layout.fragment_inquiry_withfb;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        initView();

        return rootView;
    }

    @Override
    protected void initView() {
        // 初始化房本数据
        fbStateList.add("无房本");
        fbStateList.add("有房本");

        // 初始化规划用途
        planForList.add("住宅");
        planForList.add("公寓");
        planForList.add("别墅");

        // 初始化抵押情况
        pledgeList.add("一抵");
        pledgeList.add("二抵");

        tvFbContent.setText((String) fbStateList.get(0));
        etHouseLocation.setVisibility(View.VISIBLE);
        rlHouseArea.setVisibility(View.VISIBLE);
        rlPlanFor.setVisibility(View.VISIBLE);
        rlSecoundSum.setVisibility(View.GONE);
        tvUpload.setVisibility(View.GONE);
        ivUpload.setVisibility(View.GONE);

        listViewAdapter = new ListViewAdapter(mContext);

        etSecoundSum.addTextChangedListener(new DecimalTextWatcher());
        etLiveArea.addTextChangedListener(new DecimalTextWatcher());

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    private void showFbPopup() {
        PopupViewUtil.showListPopupView(mContext, rlFb, listViewAdapter, fbStateList, new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tvFbContent.setText((String) fbStateList.get(position));

                if (position == 0) {
                    etHouseLocation.setVisibility(View.VISIBLE);
                    rlHouseArea.setVisibility(View.VISIBLE);
                    rlPlanFor.setVisibility(View.VISIBLE);
                    tvUpload.setVisibility(View.GONE);
                    ivUpload.setVisibility(View.GONE);
                } else if (position == 1) {
                    etHouseLocation.setVisibility(View.GONE);
                    rlHouseArea.setVisibility(View.GONE);
                    rlPlanFor.setVisibility(View.GONE);
                    tvUpload.setVisibility(View.VISIBLE);
                    ivUpload.setVisibility(View.VISIBLE);
                }
                PopupViewUtil.dismiss();
            }
        });
    }

    final private int REQUEST_CODE_ASK_PERMISSIONS = 123;

    @OnClick({R.id.rl_fb, R.id.rl_plan_for, R.id.rl_pledge, R.id.iv_upload, R.id.btn_apply})
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.rl_fb:
                showFbPopup();
                break;

            case R.id.rl_plan_for:
                PopupViewUtil.showListPopupView(mContext, rlPlanFor, listViewAdapter, planForList, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        tvPlanFor.setText((String) planForList.get(position));
                        PopupViewUtil.dismiss();
                    }
                });
                break;
            case R.id.rl_pledge:

                PopupViewUtil.showListPopupView(mContext, rlPledge, listViewAdapter, pledgeList, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (position == 0) {
                            rlSecoundSum.setVisibility(View.GONE);
                        } else if (position == 1) {
                            rlSecoundSum.setVisibility(View.VISIBLE);
                        }
                        pledge = position + 1 + "";
                        tvPledge.setText((String) pledgeList.get(position));
                        PopupViewUtil.dismiss();
                    }
                });
                break;

            case R.id.iv_upload:
                // 6.0以上做 permission 判断

                if (Build.VERSION.SDK_INT >= 23) {
                    int has_write_permission = mContext.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    if (has_write_permission != PackageManager.PERMISSION_GRANTED) {
                        mContext.requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                REQUEST_CODE_ASK_PERMISSIONS);
                        return;
                    }
                }

                upLoadImage("上传房本照片");
                break;

            case R.id.btn_apply:
                if (SharePrefUtil.getBoolean(mContext, ShareKey.isLogin, false)) {
                    if (checkInquiry()) applyInquiry1();
                } else {
                    LoginActivity.lauch(mContext, LoginActivity.TYPE_LOGIN);
                }

                break;
        }
    }

    // 照片
    private static final int FROM_CAMERA = 0x00000001;
    private static final int FROM_FILE = 0x00000002;
    private Uri imgUri;

    private void upLoadImage(String actionName) {

        DialogUtil.showAlertDialog(mContext, actionName, "", "相册", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 方式1，直接打开图库，只能选择图库的图片
                Intent i = new Intent(Intent.ACTION_PICK);
                //i.setType("image/*");
                i.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                // 方式2，会先让用户选择接收到该请求的APP，可以从文件系统直接选取图片
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
                intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                // 设置数据类型  要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
                intent.setType("image/*");
                startActivityForResult(i, FROM_FILE);


            }
        }, "拍照", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                imgUri = Uri.fromFile(new File(mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
                        String.valueOf(System.currentTimeMillis()) + ".png"));
                Log.e("xyd", "拍照保存的地址是：" + imgUri);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
                startActivityForResult(intent, FROM_CAMERA);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        LogUtil.e("xyd", "resultCode:" + resultCode + "  requestCode:" + requestCode);
        if (resultCode != RESULT_OK) {

            return;
        }
        switch (requestCode) {

            case FROM_FILE:
                Uri contentUri = data.getData();
                LogUtil.e("xyd", "从图库中获得的图片 contentUrl.getpath 是：" + contentUri.getPath());
                LogUtil.e("xyd", "从图库中获得的图片 contentUrl.toString 是：" + contentUri.toString());

                // 红米3 contentUri        file:///storage/emulated/0/DCIM/Camera/IMG_20170302_144902_HDR.jpg
                // 红米3 getPath        /storage/emulated/0/DCIM/Camera/IMG_20170302_144902_HDR.jpg
                // meizu getpath       /external/images/media/18029
                // 红米2A contenturi   content://media/external/images/media/18029

                // 不同手机从相册返回的路径格式不一致
                if ("content".equalsIgnoreCase(contentUri.getScheme())) {
                    imgUri = Uri.parse(FileUtil.getRealPathFromContentURI(mContext, contentUri));
                    LogUtil.e("xyd", "从图库中获得的图片 content.getlastpath 是：" + contentUri.getLastPathSegment());
                    LogUtil.e("xyd", "从图库中获得的图片 url 是：" + FileUtil.getRealPathFromContentURI(mContext, contentUri));
                } else if ("file".equalsIgnoreCase(contentUri.getScheme())) {
                    imgUri = Uri.parse(contentUri.getPath());
                }

                if (imgUri != null) {
                    if (FileUtil.getFileSize(imgUri.getPath()) > 1024 * 1024 * 2) {
                        imgUri = Uri.parse(ImageUtil.compressImage(mContext, imgUri.getPath(), 720, 960, 0));
                    }
                }
                LogUtil.e("xyd", imgUri.toString());
                ivUpload.setBackgroundDrawable(null);
                ImageUtil.displayImage(ImageUtil.URI_PREFIX_FILE + imgUri.toString(), ivUpload);
                break;
            case FROM_CAMERA:

                imgUri = Uri.parse(ImageUtil.compressImage(mContext, imgUri.getPath(), 720, 960, 0));
                LogUtil.e("xyd", "image frome camera path is " + imgUri.getPath());
                ivUpload.setBackgroundDrawable(null);
                ImageUtil.displayImage(ImageUtil.URI_PREFIX_FILE + imgUri.toString(), ivUpload);
                break;
        }
    }


    private boolean checkInquiry() {

        fbStation = tvFbContent.getText().toString().trim();
        houseLocation = etHouseLocation.getText().toString().trim();
        areaName = etAreaName.getText().toString().trim();
        liveArea = etLiveArea.getText().toString().trim();
        planFor = tvPlanFor.getText().toString().trim();
        //pledge = tvPledge.getText().toString().trim();
        secondSum = etSecoundSum.getText().toString().trim();

        // 无房本 ： 房屋所在地，小区名称，建筑面积，规划用途，抵押情况
        // 有房本 ：             小区名称，                   抵押情况，图片


        if ("无房本".equals(fbStation)) {

            if (TextUtils.isEmpty(houseLocation)) {
                ToastUtil.showToast("请输入房屋所在地");
                return false;
            }

        }

        // 小区名称 限制 50 中文
        if (TextUtils.isEmpty(areaName)) {
            ToastUtil.showToast("请输入小区名称");
            return false;
        }

        if (areaName.length() > 50) {
            // 光标离开时
            ToastUtil.showToast("小区名称输入文字数超限！");
            return false;
        }

        // 建筑面积 小数点后两位   否则提示格不正确
        if ("无房本".equals(fbStation)) {
            if (TextUtils.isEmpty(liveArea)) {
                ToastUtil.showToast("请输入建筑面积");
                return false;
            }

            if (TextUtils.isEmpty(planFor)) {
                ToastUtil.showToast("请选择规划用途");
                return false;
            }
        }

        if (TextUtils.isEmpty(pledge)) {
            ToastUtil.showToast("请选择抵押情况");
            return false;
        }

        if ("2".equals(pledge)) {

            if (TextUtils.isEmpty(secondSum)) {
                ToastUtil.showToast("一抵余额输入不能为空");
                return false;
            }

        }

        if ("有房本".equals(fbStation)) {
            if (imgUri != null && !TextUtils.isEmpty(imgUri.getPath())) {
                return true;
            } else {
                ToastUtil.showToast("请选择房本照片！");
                return false;
            }
        }

        return true;
    }


    private void applyInquiry1() {

        btnApply.setEnabled(false);
        if ("无房本".equalsIgnoreCase(fbStation)) {
            DialogUtil.showLoadingDialog(mContext, "请求中");
        } else {
            DialogUtil.showLoadingDialog(mContext, "上传中，请稍后...");
        }

        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("userId", SharePrefUtil.getString(mContext, ShareKey.UserId, ""));

        // 有房本
        if ("有房本".equalsIgnoreCase(fbStation)) {

            builder.addFormDataPart("areaName", areaName)
                    .addFormDataPart("housingMortgage", pledge);

            // 有房本、且二抵
            if ("2".equalsIgnoreCase(pledge)) {
                builder.addFormDataPart("mortgageAmount", secondSum);
            }

            RequestBody fileBody = RequestBody.create(MediaType.parse("image/png"), new File(imgUri.getPath()));
            builder.addFormDataPart("pic", "uploadImage.png", fileBody);
        }

        // 无房本
        if ("无房本".equalsIgnoreCase(fbStation)) {
            builder.addFormDataPart("roomAddress", houseLocation)
                    .addFormDataPart("areaName", areaName)
                    .addFormDataPart("housingArea", liveArea)
                    .addFormDataPart("housingType", planFor)
                    .addFormDataPart("housingMortgage", pledge);
            // 无房本、且二抵
            if ("2".equalsIgnoreCase(pledge)) {
                builder.addFormDataPart("mortgageAmount", secondSum);
            }

        }

        builder.addFormDataPart("userSource", "app");

        MultipartBody requestBody = builder.build();


        final Request request = new Request.Builder()
                .url(Url.HOST_BASE + "/api/userCenter/rest/fyd/inquiry/save")
                .post(requestBody)
                .build();

        okhttp3.Call call1 = RetrofitSingleton.getOkHttpClient().newCall(request);
        call1.enqueue(new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, final IOException e) {

                LogUtil.e("e", e.toString());

                mContext.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        btnApply.setEnabled(true);
                        if (e.toString().contains("SocketTimeoutException")) {
                            ToastUtil.showToast("网络连接超时");
                        }
                        DialogUtil.dismissLoadingDialog(mContext);
                    }
                });
            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) {
                if (response.isSuccessful()) {

                    try {
                        String s = response.body().string();
                        Gson gson = new Gson();
                        HttpResult httpResult = gson.fromJson(s, HttpResult.class);
                        if (httpResult.getStatus() == 0) {
                            ToastUtil.showToast("您的申请已经提交成功");
                            EventBus.getDefault().post(BusKey.POST_inquiryReport);
                            MainActivity.launch(mContext,1);
                            //mContext.finish();
                        } else {
                            ToastUtil.showToast(httpResult.getMsg());
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtil.showToast("申请提交失败");
                }
                mContext.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        btnApply.setEnabled(true);
                        DialogUtil.dismissLoadingDialog(mContext);
                    }
                });

            }
        });

    }


}
